package ru.home.documentmanager.controller;

import javax.annotation.Resource;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

import ru.home.documentmanager.model.User;
import ru.home.documentmanager.model.dto.UserDTO;
import ru.home.documentmanager.model.security.UserRole;
import ru.home.documentmanager.service.UserDataService;
import ru.home.documentmanager.service.UserService;

@Controller
public class AuthController {

    @Resource
    private UserService userService;

    @Resource
    private UserDataService userDataService;

    @Autowired
    private PasswordEncoder encoder;

    @RequestMapping(value = "/login", method = RequestMethod.GET)
    public ModelAndView login(
            @RequestParam(value = "fail", required = false) String fail) {
        ModelAndView model = new ModelAndView();
        if (fail != null) {
            model.addObject("fail", "Неверный логин/пароль");
        }
        model.setViewName("login");
        return model;
    }

    @RequestMapping("login/fail")
    public String loginFail() {
        return "fail";
    }

    @RequestMapping("/register")
    public String register() {
        return "register";
    }

    @RequestMapping(value = "/register/save", method = RequestMethod.POST)
    public String createUser(UserDTO userDTO) {
        User user = userService.findByUsername(userDTO.getUsername());

        if (user != null) {
            return "redirect:/error";
        } else {
            User newUser = userDTO.createUser();
            newUser.setUserRole(UserRole.USER);
            newUser.setPassword(encoder.encode(newUser.getPassword()));
            userService.save(newUser);
            return "redirect:/login";
        }
    }
}
